package chaoyue.study.service;

import chaoyue.study.domain.LoginUser;
import chaoyue.study.domain.LoginUserParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    public static final Map<String, LoginUser> CACHE = new ConcurrentHashMap<>();

    /**
     * 自定义登录
     */
    public String login(LoginUserParam user) {
        // 调用 AuthenticationManager 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 判断认证结果 如果认证失败 则 authenticate 为null
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        // 认证通过 生成token 一般会存redis 这边使用本地缓存代替
        String token = getToken();
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal(); //LoginUser是通过我们自己实现的UserDetailsServiceImpl去获取的
        CACHE.put(token, loginUser);
        return token;
    }

    /**
     * 自定义退出登录
     * 删除Redis中缓存的用户信息，这边使用本地缓存代替
     */
    public String logout(String token){
        // 删除缓存中的值
        CACHE.remove(token);
        return "退出成功";
    }

    private String getToken() {
        return UUID.randomUUID().toString();
    }
}
